from flask import Flask
import pymysql

app = Flask(__name__)

# MySQL配置（按需修改）
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': '123456',
    'database': 'mydb',
    'charset': 'utf8mb4'
}

# 测试路由
@app.route('/')
def hello():
    # 连接数据库
    conn = pymysql.connect(**db_config)
    cursor = conn.cursor()
    
    # 创建表（首次运行）
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS books (
            id INT AUTO_INCREMENT PRIMARY KEY,
            title VARCHAR(100)
        )
    ''')
    
    # 插入数据
    cursor.execute("INSERT INTO books (title) VALUES ('Flask Guide')")
    conn.commit()
    
    # 查询数据
    cursor.execute("SELECT * FROM books")
    books = cursor.fetchall()
    
    cursor.close()
    conn.close()
    
    return f'Books: {books}'

if __name__ == '__main__':
    app.run(debug=True)